package com.sucker.infoservice.controller;

import com.sucker.infoservice.handler.VideoHttpRequestHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;

@Controller
@RequestMapping("/player")
public class PlayerController {

    @Resource
    private VideoHttpRequestHandler videoHttpRequestHandler;

    private final String PREFIX = Objects.requireNonNull
            (
                    this.getClass()
                            .getClassLoader()
                            .getResource("")
            ).getPath();
    private final String AUDIO_PREFIX = PREFIX + "audio/";

    private final String VIDEO_PREFIX = PREFIX + "video/";

    @GetMapping("/audio")
    public ResponseEntity<byte[]> playMusic(@RequestParam("name") String name) {
        File file = new File(AUDIO_PREFIX + name);
        byte[] bytes;
        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        try {
            bytes = Files.readAllBytes(file.toPath());
            return ResponseEntity.ok(bytes);
        } catch (IOException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/video")
    public void playVideo(HttpServletRequest request,
                          HttpServletResponse response,
                          @RequestParam("name") String name) throws Exception {
        File file = new File(VIDEO_PREFIX + name);
        Path path = file.toPath();
        if (Files.exists(path)) {
            String mimeType = Files.probeContentType(path);
            if (!StringUtils.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(VideoHttpRequestHandler.ATTR_FILE, path);
            videoHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }
}
